package com.cloud.user.config;

import feign.Feign;
import feign.codec.Encoder;
import feign.form.FormEncoder;
import okhttp3.ConnectionPool;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;


/**
 * 配置 okhttp 与连接池
 * TIPS：需要在使用Feign的客户端加入相应的pom依赖和配置文件配置
 *
 * @author qinxh
 * @since 2019-10-19
 */
@Configuration
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
public class OkHttpConfig {

    /**
     * 默认老外留给你彩蛋中文乱码，加上它就 OK
     *
     * @return Encoder
     */
    @Bean
    public Encoder encoder() {

        return new FormEncoder();
    }

    @Bean
    public okhttp3.OkHttpClient okHttpClient() {

        return new okhttp3.OkHttpClient.Builder()
                // 设置连接超时
                .connectTimeout(10, TimeUnit.SECONDS)
                // 设置读超时
                .readTimeout(10, TimeUnit.SECONDS)
                // 设置写超时
                .writeTimeout(10, TimeUnit.SECONDS)
                // 是否自动重连
                .retryOnConnectionFailure(true)
                // ConnectionPool 默认创建5个线程，保持5分钟长连接
                .connectionPool(new ConnectionPool(10, 5L, TimeUnit.MINUTES))
                .build();
    }
}
